using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace axCommerce.Data
{
	[DataObject]
	[Serializable]
	public partial class EmailTemplate
	{
		#region Constants

		private const string TableName = "[dbo].[EmailTemplate]";

		#endregion

		#region Properties

		public int? EmailTemplateId { get; set; }
		public int? EmailTemplateTypeId { get; set; }
		public string Subject { get; set; }
		public string Content { get; set; }
		public string Description { get; set; }
		public DateTime? CreatedDate { get; set; }
		public DateTime? LastModifiedDate { get; set; }
		public bool? IsDeleted { get; set; }

		#endregion

		#region Methods

		#region Mapping Methods

		protected void MapTo(DataSet ds)
		{
			if (ds == null)
				ds = new DataSet();

			if (ds.Tables[TableName] == null)
				ds.Tables.Add(TableName);

			ds.Tables[TableName].Columns.Add("EmailTemplateId", typeof (Int32));
			ds.Tables[TableName].Columns.Add("EmailTemplateTypeId", typeof(Int32));
			ds.Tables[TableName].Columns.Add("Subject", typeof(String));
			ds.Tables[TableName].Columns.Add("Content", typeof(String));
			ds.Tables[TableName].Columns.Add("Description", typeof (String));
			ds.Tables[TableName].Columns.Add("CreatedDate", typeof (DateTime));
			ds.Tables[TableName].Columns.Add("LastModifiedDate", typeof (DateTime));
			ds.Tables[TableName].Columns.Add("IsDeleted", typeof (Boolean));

			DataRow dr = ds.Tables[TableName].NewRow();

			dr["EmailTemplateId"] = EmailTemplateId ?? (object) DBNull.Value;
			dr["EmailTemplateTypeId"] = EmailTemplateTypeId ?? (object)DBNull.Value;
			dr["Subject"] = Subject ?? (object)DBNull.Value;
			dr["Content"] = Content ?? (object)DBNull.Value;
			dr["Description"] = Description ?? (object) DBNull.Value;
			dr["CreatedDate"] = CreatedDate ?? (object) DBNull.Value;
			dr["LastModifiedDate"] = LastModifiedDate ?? (object) DBNull.Value;
			dr["IsDeleted"] = IsDeleted ?? (object) DBNull.Value;

			ds.Tables[TableName].Rows.Add(dr);
		}

		protected void MapFrom(DataRow dr)
		{
			EmailTemplateId = dr["EmailTemplateId"] != DBNull.Value
			                  	? Convert.ToInt32(dr["EmailTemplateId"])
			                  	: EmailTemplateId = null;
			EmailTemplateTypeId = dr["EmailTemplateTypeId"] != DBNull.Value
								? Convert.ToInt32(dr["EmailTemplateTypeId"])
								: EmailTemplateTypeId = null;
			Subject = dr["Subject"] != DBNull.Value ? Convert.ToString(dr["Subject"]) : Subject = null;
			Content = dr["Content"] != DBNull.Value ? Convert.ToString(dr["Content"]) : Content = null;
			Description = dr["Description"] != DBNull.Value ? Convert.ToString(dr["Description"]) : Description = null;
			CreatedDate = dr["CreatedDate"] != DBNull.Value ? Convert.ToDateTime(dr["CreatedDate"]) : CreatedDate = null;
			LastModifiedDate = dr["LastModifiedDate"] != DBNull.Value
			                   	? Convert.ToDateTime(dr["LastModifiedDate"])
			                   	: LastModifiedDate = null;
			IsDeleted = dr["IsDeleted"] != DBNull.Value ? Convert.ToBoolean(dr["IsDeleted"]) : IsDeleted = null;

			FillEmailTemplateTypeInfo();
		}

		private static List<EmailTemplate> MapFrom(DataSet ds)
		{
			// Initialise Collection.
			List<EmailTemplate> objects = new List<EmailTemplate>();

			// Validation.
			if (ds == null)
				throw new ApplicationException("Cannot map to dataset null.");
			if (ds.Tables[TableName].Rows.Count == 0)
				return objects;

			if (ds.Tables[TableName] == null)
				throw new ApplicationException("Cannot find table [dbo].[EmailTemplate] in DataSet.");

			if (ds.Tables[TableName].Rows.Count < 1)
				throw new ApplicationException("Table [dbo].[EmailTemplate] is empty.");

			// Map DataSet to Instance.
			foreach (DataRow dr in ds.Tables[TableName].Rows)
			{
				var instance = new EmailTemplate();
				instance.MapFrom(dr);
				objects.Add(instance);
			}

			// Return collection.
			return objects;
		}

		#endregion

		#region CRUD Methods

		private static EmailTemplate Get(Int32 emailTemplateId)
		{
			EmailTemplate instance = new EmailTemplate();

			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplate_SELECT";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, emailTemplateId))
			{
				using (DataSet ds = db.ExecuteDataSet(dbCommand))
				{
					if (ds == null || ds.Tables[0].Rows.Count == 0)
						throw new ApplicationException(String.Format("Could not get EmailTemplate ID:{0} from Database.", emailTemplateId));
					// Return results.
					ds.Tables[0].TableName = TableName;

					instance.MapFrom(ds.Tables[0].Rows[0]);
				}
			}
			return instance;
		}

		#region INSERT

		private void Insert(Int32? emailTemplateTypeId, String subject, String content, String description, DateTime? createdDate, DateTime? lastModifiedDate,
		                   Boolean? isDeleted, DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplate_INSERT";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, emailTemplateTypeId, subject, content, description, createdDate, lastModifiedDate, isDeleted))
			{
				EmailTemplateId = Convert.ToInt32(transaction == null ? db.ExecuteScalar(dbCommand) : db.ExecuteScalar(dbCommand, transaction));
			}
		}

		/// <summary>
		/// Insert current EmailTemplate to database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		private void Insert(DbTransaction transaction = null)
		{
			Insert(EmailTemplateTypeId, Subject, Content, Description, CreatedDate, LastModifiedDate, IsDeleted, transaction);
		}

		#endregion

		#region UPDATE

		private static void Update(Int32? emailTemplateId, Int32 emailTemplateTypeId, String subject, String content, String description,
		                          DateTime? createdDate, DateTime? lastModifiedDate, Boolean? isDeleted,
		                          DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplate_UPDATE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand))
			{
				db.DiscoverParameters(dbCommand);
				dbCommand.Parameters["@emailTemplateId"].Value = emailTemplateId;
				dbCommand.Parameters["@emailTemplateTypeId"].Value = emailTemplateTypeId;
				dbCommand.Parameters["@subject"].Value = subject;
				dbCommand.Parameters["@content"].Value = content;
				dbCommand.Parameters["@description"].Value = description;
				dbCommand.Parameters["@createdDate"].Value = createdDate;
				dbCommand.Parameters["@lastModifiedDate"].Value = lastModifiedDate;
				dbCommand.Parameters["@isDeleted"].Value = isDeleted;

				if (transaction == null)
					db.ExecuteNonQuery(dbCommand);
				else
					db.ExecuteNonQuery(dbCommand, transaction);
			}
		}

		private static void Update(EmailTemplate emailTemplate)
		{
			emailTemplate.Update();
		}

		private static void Update(EmailTemplate emailTemplate, DbTransaction transaction)
		{
			emailTemplate.Update(transaction);
		}

		/// <summary>
		/// Updates changes to the database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		private void Update(DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplate_UPDATE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand))
			{
				db.DiscoverParameters(dbCommand);
				dbCommand.Parameters["@emailTemplateId"].SourceColumn = "EmailTemplateId";
				dbCommand.Parameters["@emailTemplateTypeId"].SourceColumn = "EmailTemplateTypeId";
				dbCommand.Parameters["@subject"].SourceColumn = "Subject";
				dbCommand.Parameters["@content"].SourceColumn = "Content";
				dbCommand.Parameters["@description"].SourceColumn = "Description";
				dbCommand.Parameters["@createdDate"].SourceColumn = "CreatedDate";
				dbCommand.Parameters["@lastModifiedDate"].SourceColumn = "LastModifiedDate";
				dbCommand.Parameters["@isDeleted"].SourceColumn = "IsDeleted";

				using (DataSet ds = new DataSet())
				{
					MapTo(ds);
					ds.AcceptChanges();
					ds.Tables[0].Rows[0].SetModified();
					if (transaction == null)
						db.UpdateDataSet(ds, TableName, null, dbCommand, null, UpdateBehavior.Standard);
					else
						db.UpdateDataSet(ds, TableName, null, dbCommand, null, transaction);
				}
			}
		}

		#endregion

		#region DELETE

		private static void Delete(Int32? emailTemplateId, DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplate_DELETE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, emailTemplateId))
			{
				if (transaction != null)
				{
					db.ExecuteNonQuery(dbCommand, transaction);
				}
				else
				{
					db.ExecuteNonQuery(dbCommand);
				}
			}
		}

		/// <summary>
		/// Delete current EmailTemplate from database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		private void Delete(DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplate_DELETE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, EmailTemplateId))
			{
				if (transaction != null)
				{
					db.ExecuteNonQuery(dbCommand, transaction);
				}
				else
				{
					db.ExecuteNonQuery(dbCommand);
				}
			}
			EmailTemplateId = null;
		}

		#endregion

		#region SEARCH

		private static List<EmailTemplate> Search(Int32? emailTemplateId = null, Int32? emailTemplateTypeId = null, String subject = null, String content = null, String description = null,
		                                     DateTime? createdDate = null, DateTime? lastModifiedDate = null, Boolean? isDeleted = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspEmailTemplate_SEARCH";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, emailTemplateId, emailTemplateTypeId, subject, content, description, createdDate, lastModifiedDate, isDeleted))
			{
				using (DataSet ds = db.ExecuteDataSet(dbCommand))
				{
					ds.Tables[0].TableName = TableName;
					return MapFrom(ds);
				}
			}
		}


		private static List<EmailTemplate> Search(EmailTemplate searchObject)
		{
			return Search(searchObject.EmailTemplateId, searchObject.EmailTemplateTypeId, searchObject.Subject, searchObject.Content, searchObject.Description,
			              searchObject.CreatedDate, searchObject.LastModifiedDate, searchObject.IsDeleted);
		}

		#endregion

		#endregion

		#endregion
	}
}